package com.example.fourm.services.impl;

import com.example.fourm.common.AppResult;
import com.example.fourm.common.ResultCode;
import com.example.fourm.dao.ArticleMapper;
import com.example.fourm.dao.ArticleReplyMapper;
import com.example.fourm.exception.ApplicationException;
import com.example.fourm.model.Article;
import com.example.fourm.model.ArticleReply;
import com.example.fourm.services.IArticleReplyService;
import com.example.fourm.services.IArticleService;
import com.example.fourm.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private IArticleService articleService;
    @Transactional
    @Override
    public void create(ArticleReply articleReply) {
        if(articleReply == null ||articleReply.getArticleId()==null || StringUtil.isEmpty(articleReply.getContent()) || articleReply.getContent().trim().equals("")){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        Article article = articleService.selectById(articleReply.getArticleId());
        if(article==null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()+" 该文章不存在");
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.getMessage()+" 回复失败！！");
        }
        if(article.getState() != 0){
            log.warn(ResultCode.FAILED.getMessage()+" 帖子状态异常");
        }
        articleReply.setReplyUserId(null);
        articleReply.setReplyId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date now = new Date();
        articleReply.setCreateTime(now);
        articleReply.setUpdateTime(now);
        int row = articleReplyMapper.insertSelective(articleReply);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.getMessage() +" 回复失败");
            throw new ApplicationException(ResultCode.ERROR_SERVICES.getMessage());
        }
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("回复成功^^");
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if(articleId == null || articleId == 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(articleId);
        return articleReplies;
    }
}
